<template>
  <cs-form
    ref="formRef"
    v-model="store.listPageFormData"
    :items="items"
    component-full-width
  />
</template>

<script setup lang="ts">
  import { computed, inject, reactive, toRef } from 'vue'
  import { useApiConfig } from '../hooks'

  import type { ListPageFormData, Store } from '../types'

  const store = inject('CSDEV_CODE_VIEW_STORE', {} as Store)
  const formRef = toRef(store, 'listPageFormRef')
  const { apiConfig: listPageApiConfig } = useApiConfig(store, 'listPage')

  /**
   * @description 提取范型中的类型
   * @param str 类型名
   * @returns 返回具体类型
   */
  const extractGenericType = (str: string) => {
    // 使用正则表达式匹配 < > 之间的内容
    const regex = /<([^>]+)>/
    const match = str.match(regex)

    if (match) {
      // 提取第一个匹配到的内容，即泛型类型
      const genericType = match[1]
      return genericType
    } else {
      // 如果没有匹配到泛型类型，则直接返回原始字符串
      return str
    }
  }

  const properties = computed(() => {
    if (!listPageApiConfig.value) {
      return
    }
    const VO =
      store.codeConfig.dataSchemasNameMap?.[
        extractGenericType(listPageApiConfig.value.response.schema.name)
      ]
    return VO?.jsonSchema.properties
  })

  const rowKeyOptions = computed(() => {
    const options: Array<{ label: string, value: string }> = []
    for (const key in properties.value) {
      options.push({
        label: `${key} - ${properties.value[key].description}`,
        value: key
      })
    }
    return options
  })

  const items: FormItemProps<ListPageFormData>[] = reactive([
    {
      label: '列表rowKey',
      prop: 'rowKey',
      component: 'cs-select',
      required: true,
      tooltip: '列表rowKey，通常为后端唯一ID，生成删除操作相关代码时作为ID传入',
      props: {
        options: rowKeyOptions,
        fitInputWidth: true,
        filterable: true
      }
    }
  ])
</script>
